/**
 * 地图渲染与交互
 */
const MapRenderer = {
    canvas: null,
    ctx: null,
    isDragging: false,
    lastMousePos: { x: 0, y: 0 },
    
    /**
     * 初始化地图
     */
    initialize() {
        this.canvas = document.getElementById('world-map');
        this.ctx = this.canvas.getContext('2d');
        
        // 设置初始视口偏移
        GameData.map.viewportOffset = {
            x: 0,
            y: 0
        };
        
        // 设置初始缩放
        GameData.map.zoom = 1;
        
        // 添加事件监听器
        this.setupEventListeners();
        
        // 初次渲染
        this.render();
    },
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 鼠标拖动
        this.canvas.addEventListener('mousedown', (e) => {
            this.isDragging = true;
            this.lastMousePos = {
                x: e.clientX,
                y: e.clientY
            };
        });
        
        document.addEventListener('mousemove', (e) => {
            if (!this.isDragging) return;
            
            const dx = e.clientX - this.lastMousePos.x;
            const dy = e.clientY - this.lastMousePos.y;
            
            GameData.map.viewportOffset.x += dx / GameData.map.zoom;
            GameData.map.viewportOffset.y += dy / GameData.map.zoom;
            
            this.lastMousePos = {
                x: e.clientX,
                y: e.clientY
            };
            
            this.render();
        });
        
        document.addEventListener('mouseup', () => {
            this.isDragging = false;
        });
        
        // 缩放控制
        document.getElementById('zoom-in').addEventListener('click', () => {
            this.zoom(1.2);
        });
        
        document.getElementById('zoom-out').addEventListener('click', () => {
            this.zoom(0.8);
        });
        
        document.getElementById('reset-view').addEventListener('click', () => {
            GameData.map.viewportOffset = { x: 0, y: 0 };
            GameData.map.zoom = 1;
            this.render();
        });
        
        // 鼠标滚轮缩放
        this.canvas.addEventListener('wheel', (e) => {
            e.preventDefault();
            const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
            
            // 获取鼠标在画布上的位置
            const rect = this.canvas.getBoundingClientRect();
            const mouseX = e.clientX - rect.left;
            const mouseY = e.clientY - rect.top;
            
            // 计算鼠标在世界坐标中的位置
            const worldX = mouseX / GameData.map.zoom - GameData.map.viewportOffset.x;
            const worldY = mouseY / GameData.map.zoom - GameData.map.viewportOffset.y;
            
            // 更新缩放
            GameData.map.zoom *= zoomFactor;
            
            // 限制缩放范围
            GameData.map.zoom = Math.max(0.5, Math.min(GameData.map.zoom, 3));
            
            // 调整视口偏移，使鼠标位置保持不变
            GameData.map.viewportOffset.x = mouseX / GameData.map.zoom - worldX;
            GameData.map.viewportOffset.y = mouseY / GameData.map.zoom - worldY;
            
            this.render();
        });
        
        // 点击王国
        this.canvas.addEventListener('click', (e) => {
            if (this.isDragging) return;
            
            const rect = this.canvas.getBoundingClientRect();
            const mouseX = e.clientX - rect.left;
            const mouseY = e.clientY - rect.top;
            
            // 转换为世界坐标
            const worldX = mouseX / GameData.map.zoom - GameData.map.viewportOffset.x;
            const worldY = mouseY / GameData.map.zoom - GameData.map.viewportOffset.y;
            
            // 检查是否点击了王国
            for (const kingdom of GameData.kingdoms) {
                const dx = kingdom.location.x - worldX;
                const dy = kingdom.location.y - worldY;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 王国点击半径（根据人口大小调整）
                const radius = 15 + Math.sqrt(kingdom.population) / 10;
                
                if (distance <= radius) {
                    // 显示王国详情
                    UI.showKingdomDetail(kingdom);
                    return;
                }
            }
        });
    },
    
    /**
     * 缩放地图
     * @param {number} factor - 缩放因子
     */
    zoom(factor) {
        // 获取画布中心
        const centerX = this.canvas.width / 2;
        const centerY = this.canvas.height / 2;
        
        // 计算中心点在世界坐标中的位置
        const worldCenterX = centerX / GameData.map.zoom - GameData.map.viewportOffset.x;
        const worldCenterY = centerY / GameData.map.zoom - GameData.map.viewportOffset.y;
        
        // 更新缩放
        GameData.map.zoom *= factor;
        
        // 限制缩放范围
        GameData.map.zoom = Math.max(0.5, Math.min(GameData.map.zoom, 3));
        
        // 调整视口偏移，使中心点保持不变
        GameData.map.viewportOffset.x = centerX / GameData.map.zoom - worldCenterX;
        GameData.map.viewportOffset.y = centerY / GameData.map.zoom - worldCenterY;
        
        this.render();
    },
    
    /**
     * 渲染地图
     */
    render() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 应用变换
        this.ctx.save();
        this.ctx.translate(GameData.map.viewportOffset.x * GameData.map.zoom, GameData.map.viewportOffset.y * GameData.map.zoom);
        this.ctx.scale(GameData.map.zoom, GameData.map.zoom);
        
        // 渲染地形
        this.renderTerrain();
        
        // 渲染资源点
        this.renderResourcePoints();
        
        // 渲染危险区域
        this.renderDangerZones();
        
        // 渲染王国
        this.renderKingdoms();
        
        // 恢复变换
        this.ctx.restore();
    },
    
    /**
     * 渲染地形
     */
    renderTerrain() {
        const width = CONFIG.MAP.WIDTH;
        const height = CONFIG.MAP.HEIGHT;
        const tileSize = 10; // 每个地形块的大小
        
        // 计算可见区域
        const visibleLeft = -GameData.map.viewportOffset.x;
        const visibleTop = -GameData.map.viewportOffset.y;
        const visibleRight = visibleLeft + this.canvas.width / GameData.map.zoom;
        const visibleBottom = visibleTop + this.canvas.height / GameData.map.zoom;
        
        // 计算可见的地形块范围
        const startX = Math.max(0, Math.floor(visibleLeft / tileSize));
        const startY = Math.max(0, Math.floor(visibleTop / tileSize));
        const endX = Math.min(width / tileSize, Math.ceil(visibleRight / tileSize));
        const endY = Math.min(height / tileSize, Math.ceil(visibleBottom / tileSize));
        
        // 渲染可见的地形块
        for (let y = startY; y < endY; y++) {
            for (let x = startX; x < endX; x++) {
                const terrainType = GameData.map.terrain[Math.floor(y * tileSize / height * GameData.map.terrain.length)][Math.floor(x * tileSize / width * GameData.map.terrain[0].length)];
                const color = CONFIG.MAP.TERRAIN_TYPES[terrainType].color;
                
                this.ctx.fillStyle = color;
                this.ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);
            }
        }
    },
    
    /**
     * 渲染资源点
     */
    renderResourcePoints() {
        this.ctx.fillStyle = '#d4af37'; // 金色
        
        for (const point of GameData.map.resourcePoints) {
            this.ctx.beginPath();
            this.ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
            this.ctx.fill();
        }
    },
    
    /**
     * 渲染危险区域
     */
    renderDangerZones() {
        this.ctx.fillStyle = '#c93c3c'; // 红色
        
        for (const zone of GameData.map.dangerZones) {
            this.ctx.beginPath();
            this.ctx.moveTo(zone.x, zone.y - 7);
            this.ctx.lineTo(zone.x + 7, zone.y);
            this.ctx.lineTo(zone.x, zone.y + 7);
            this.ctx.lineTo(zone.x - 7, zone.y);
            this.ctx.closePath();
            this.ctx.fill();
        }
    },
    
    /**
     * 渲染王国
     */
    renderKingdoms() {
        for (const kingdom of GameData.kingdoms) {
            // 计算王国圆圈大小（基于人口），不超过最大半径
            const radius = Math.min(
                15 + Math.sqrt(kingdom.population) / 10,
                CONFIG.MAP.MAX_KINGDOM_RADIUS
            );
            
            // 绘制王国区域
            this.ctx.fillStyle = kingdom.color;
            this.ctx.beginPath();
            this.ctx.arc(kingdom.location.x, kingdom.location.y, radius, 0, Math.PI * 2);
            this.ctx.fill();
            
            // 绘制边框
            this.ctx.strokeStyle = '#fff';
            this.ctx.lineWidth = 2;
            this.ctx.stroke();
            
            // 绘制王国名称
            this.ctx.fillStyle = '#fff';
            this.ctx.font = '12px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText(kingdom.name, kingdom.location.x, kingdom.location.y + radius + 15);
        }
    }
};